<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-popconfirm
            v-if="item.btnKey === 'publishToApp'"
            title="是否确认发布至App？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handlePublishApp()"
          >
            <a-button :key="index" :type="item.btnType" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            v-else-if="item.btnKey === 'unpublish'"
            title="是否确认取消发布？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleUnpublish()"
          >
            <a-button :key="index" :type="item.btnType" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-button v-else :key="index" :type="item.btnType" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ code: record.code })">
          {{ record.code }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopExtendShopExtendClsList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, nextTick, onMounted, ref } from 'vue';
  import { useGo } from '/@/hooks/web/usePage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { BasicTable, useTable, ActionItem, BasicColumn } from '/@/components/Table';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import {
    shopExtendClsDelete,
    shopExtendClsDisable,
    shopExtendClsEnable,
    batchPublishToApp,
    unPublishedToApp,
  } from '/@/api/shop/product/shopExtendCls';
  import InputForm from './form.vue';

  const props = defineProps({
    treeCode: String,
  });

  const go = useGo();

  let title = ref('');
  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});

  const { t } = useI18n('shop.product.shopExtendCls');
  const { showMessage } = useMessage();
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 4, md: 6 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑商品分类'),
        onClick: handleForm.bind(this, { code: record.code }),
        auth: 'shop:product:shopExtendCls:edit',
      },
      {
        icon: 'ant-design:stop-outlined',
        color: 'error',
        title: t('停用商品分类'),
        popConfirm: {
          title: t('是否确认停用商品分类'),
          confirm: handleDisable.bind(this, { code: record.code }),
        },
        auth: 'shop:product:shopExtendCls:edit',
        ifShow: () => record.status === '0',
      },
      {
        icon: 'ant-design:check-circle-outlined',
        color: 'success',
        title: t('启用商品分类'),
        popConfirm: {
          title: t('是否启用商品分类'),
          confirm: handleEnable.bind(this, { code: record.code }),
        },
        auth: 'shop:product:shopExtendCls:edit',
        ifShow: () => record.status === '2',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setProps, getForm, getSelectRowKeys }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  onMounted(async () => {
    const res = await listSet({ viewCode: 'shop_extend_cls' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btnAdd') {
        item.do = () => handleForm({});
      }
      if (item.btnKey === 'publishToApp') {
        item.do = () => handlePublishApp();
      }
      if (item.btnKey === 'unpublish') {
        item.do = () => handleUnpublish();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        code: props.treeCode,
      });
      reload();
    },
  );

  function fetchSuccess() {
    if (props.treeCode) {
      nextTick(expandAll);
    }
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDisable(record: Recordable) {
    const res = await shopExtendClsDisable(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleEnable(record: Recordable) {
    const res = await shopExtendClsEnable(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleDelete(record: Recordable) {
    const res = await shopExtendClsDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 发布至APP
  async function handlePublishApp() {
    const ids = getSelectRowKeys();
    if (ids.length) {
      const res = await batchPublishToApp({
        ids: ids.join(','),
      });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage(t('请先选择一个商品分类！'));
    }
  }

  // 取消发布
  async function handleUnpublish() {
    const ids = getSelectRowKeys();
    if (ids.length) {
      const res = await unPublishedToApp({
        ids: ids.join(','),
      });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage(t('请先选择一个商品分类！'));
    }
  }

  function handleSuccess() {
    reload();
  }
</script>
